{% extends "base.html" %}

{% block title %}系统数据集 - {{ super() }}{% endblock %}

{% block head_extra %}
<style>
  /* 为卡片描述设置最大高度和溢出处理 */
  .dataset-description {
    max-height: 6rem; /* 约等于4行文本，可以根据实际情况调整 */
    overflow-y: auto;
    line-height: 1.5rem;
  }
  .card-compact .card-body {
      padding: 1rem; /* 调整内边距以获得更紧凑的卡片 */
  }
  .tabs-container {
    display: flex;
    align-items: center; /* 垂直居中 */
    width: 100%; /* 容器占据全部可用宽度 */
  }
  .tabs-scrollable {
    width: 80%; /* Tab区域占据80%宽度 */
    overflow-x: auto; /* 如果tabs过多则允许横向滚动 */
    -ms-overflow-style: none;  /* IE and Edge */
    scrollbar-width: none;  /* Firefox */
  }
  .tabs-scrollable::-webkit-scrollbar {
      display: none; /* Chrome, Safari, Opera */
  }
  /* Ensure the .tabs element itself (e.g., .tabs-boxed) inside .tabs-scrollable doesn't wrap its children */
  .tabs-scrollable > .tabs {
      display: flex; /* Ensure it's a flex container */
      flex-wrap: nowrap !important; /* Prevent tabs from wrapping */
      width: max-content; /* Allow container to be as wide as all tabs combined */
  }
  .tabs.tabs-boxed .tab {
      padding-left: 0.75rem; /* 调整tab内边距使其更紧凑 */
      padding-right: 0.75rem;
  }
  .search-container {
    width: 20%; /* 搜索区域占据20%宽度 */
    padding-left: 1rem; /* Add some spacing between tabs and search bar if gap is removed from parent */
  }
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="mb-8">
        <div class="flex justify-between items-center mb-4">
            <h1 class="text-3xl font-bold">评估数据集</h1>
            <div class="flex gap-2">
                <div class="form-control">
                    <label class="cursor-pointer label gap-2">
                        <span class="label-text">显示所有数据集</span>
                        <input type="checkbox" class="toggle toggle-primary toggle-sm" id="showAllToggle" 
                               {% if show_all %}checked{% endif %} />
                    </label>
                </div>
                <a href="{{ url_for('datasets.add_custom_dataset') }}" class="btn btn-primary btn-sm">
                    <i class="fas fa-plus mr-2"></i>添加自定义数据集
                </a>
            </div>
        </div>
        
        <!-- Tabs 和搜索框容器 -->
        <div class="tabs-container mb-6">
            <!-- Tabs 区域 -->
            <div class="tabs-scrollable">
                <div class="tabs tabs-boxed">
                    <a href="{{ url_for('datasets.datasets_list', category='全部') }}" 
                       class="tab {{ 'tab-active' if selected_category == '全部' or not selected_category else '' }}">全部</a>
                    {% for cat in all_categories %}
                    <a href="{{ url_for('datasets.datasets_list', category=cat.name) }}" 
                       class="tab {{ 'tab-active' if selected_category == cat.name else '' }}">{{ cat.name }}</a>
                    {% endfor %}
                </div>
            </div>
            
            <!-- 搜索框区域 -->
            <div class="search-container form-control">
                <div class="input-group input-group-sm items-center">
                    <input type="text" placeholder="搜索评估数据集…" class="input input-bordered input-sm w-full" />
                </div>
            </div>
        </div>

    </div>

    <!-- 数据集卡片列表 -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        {% if datasets %}
            {% for dataset in datasets %}
            <div class="card card-compact bg-base-100 shadow-xl border border-base-300 relative
                        {% if not dataset.is_active %}opacity-70{% endif %}">
                {% if not dataset.is_active %}
                <div class="absolute top-2 right-2 badge badge-warning">未启用</div>
                {% endif %}
                <div class="card-body">
                    <h2 class="card-title text-xl">
                        {{ dataset.name }}
                    </h2>
                    <div class="my-1">
                        {% for category_obj in dataset.categories %}
                        <span class="badge badge-ghost badge-sm mr-1 mb-1">{{ category_obj.name }}</span>
                        {% endfor %}
                        <span class="badge badge-primary badge-sm mr-1 mb-1">{{ dataset.format }}</span>
                    </div>
                    <p class="text-sm text-base-content/70 dataset-description">{{ dataset.description }}</p>
                    
                    <div class="mt-3 pt-3 border-t border-base-300/50 flex justify-between items-center text-xs text-base-content/60">
                        <div class="flex items-center">
                            <!-- 创建者图标 -->
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                            </svg>
                            <span>{{ dataset.source if dataset.source else '系统' }}</span>
                        </div>
                        <div class="flex items-center">
                            {# views 字段已移除 #}
                            {# <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                               <path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                               <path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-.001.009-.002.018-.003.027A16.996 16.996 0 0112 19c-4.478 0-8.268-2.943-9.542-7 .001-.009.002-.018.003-.027z" />
                            </svg>
                            <span class="mr-3">{{ dataset.views if dataset.views != 'N/A' else '-' }}</span> #}
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                            </svg>
                            <span>{{ dataset.publish_date if dataset.publish_date else 'N/A' }}</span>
                        </div>
                    </div>
                    <div class="card-actions justify-end mt-2">
                        {# sample_data_url 已移除, sample_data 是 JSON 字段 #}
                        <button class="btn btn-xs btn-outline btn-primary" 
                                onclick="showSampleDataModal(this)" 
                                data-sample-data='{{ dataset.dataset_info | safe if dataset.dataset_info else "{}" }}'
                                {% if not dataset.dataset_info %}disabled{% endif %}>
                            查看结构
                        </button>
                        <a href="{{ url_for('datasets.preview_dataset', dataset_id=dataset.id) }}" 
                           class="btn btn-xs btn-outline btn-secondary" 
                           title="使用ModelScope API预览数据，数据集名称来自download_url字段"
                           {% if not dataset.dataset_info %}onclick="alert('该数据集没有结构信息，无法预览'); return false;"{% endif %}
                           {% if not dataset.download_url %}onclick="alert('该数据集没有设置download_url字段，无法预览'); return false;"{% endif %}>
                           预览数据
                        </a>
                        {% if current_user and current_user.is_authenticated and dataset.dataset_type == '自建' and dataset.source == current_user.username %}
                        <button class="btn btn-xs btn-outline btn-error" 
                                onclick="confirmDeleteDataset(this)"
                                data-dataset-id="{{ dataset.id }}"
                                data-dataset-name="{{ dataset.name }}"
                                title="删除自建数据集">
                            删除
                        </button>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% endfor %}
        {% else %}
            <p class="col-span-1 md:col-span-2 text-center">没有找到符合条件的系统数据集。</p>
        {% endif %}
    </div>
</div>

<!-- 样例数据模态框 -->
<div id="sampleDataModal" class="modal">
  <div class="modal-box w-11/12 max-w-5xl">
    <h3 class="font-bold text-lg mb-4">数据集结构信息</h3>
    <div id="sampleDataContent" class="whitespace-pre-wrap bg-base-200 p-4 rounded-md max-h-96 overflow-y-auto">
      <!-- 数据集结构信息将在这里显示 -->
    </div>
    <div class="modal-action">
      <button class="btn" onclick="document.getElementById('sampleDataModal').classList.remove('modal-open');">关闭</button>
    </div>
  </div>
</div>

<!-- 删除确认模态框 -->
<div id="deleteConfirmModal" class="modal">
  <div class="modal-box">
    <h3 class="font-bold text-lg mb-4 text-error">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 inline mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
        <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L4.268 18.5c-.77.833.192 2.5 1.732 2.5z" />
      </svg>
      确认删除数据集
    </h3>
    <div class="py-4">
      <div class="alert alert-warning mb-4">
        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L4.268 18.5c-.77.833.192 2.5 1.732 2.5z" />
        </svg>
        <span>删除后将无法恢复数据集及其相关文件。</span>
      </div>
      <p id="deleteConfirmMessage" class="text-base-content">
        <!-- 删除确认消息将在这里显示 -->
      </p>
    </div>
    <div class="modal-action">
      <button class="btn btn-ghost" onclick="closeDeleteModal()">取消</button>
      <button id="confirmDeleteBtn" class="btn btn-error" onclick="executeDelete()">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
          <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
        </svg>
        确认删除
      </button>
    </div>
  </div>
</div>

<!-- 强制删除确认模态框 -->
<div id="forceDeleteModal" class="modal">
  <div class="modal-box">
    <h3 class="font-bold text-lg mb-4 text-error">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 inline mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
        <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L4.268 18.5c-.77.833.192 2.5 1.732 2.5z" />
      </svg>
      强制删除数据集
    </h3>
    <div class="py-4">
      <div class="alert alert-error mb-4">
        <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <span>危险操作：此操作将同时删除相关的评估记录！</span>
      </div>
      <p id="forceDeleteMessage" class="text-base-content mb-4">
        <!-- 强制删除消息将在这里显示 -->
      </p>
      <div class="bg-base-200 p-4 rounded-lg">
        <h4 class="font-semibold mb-2">将要删除的内容：</h4>
        <ul class="list-disc list-inside space-y-1 text-sm">
          <li>数据集本身及其文件</li>
          <li id="dependencyInfo">相关的评估数据集关联记录</li>
        </ul>
      </div>
    </div>
    <div class="modal-action">
      <button class="btn btn-ghost" onclick="closeForceDeleteModal()">取消</button>
      <button id="confirmForceDeleteBtn" class="btn btn-error" onclick="executeForceDelete()">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
          <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
        </svg>
        强制删除
      </button>
    </div>
  </div>
</div>

{% endblock %}

{% block scripts %}
{{ super() }}
<script>
function showSampleDataModal(button) {
    const sampleDataString = button.dataset.sampleData;
    const sampleDataContentElement = document.getElementById('sampleDataContent');
    const modal = document.getElementById('sampleDataModal');
    try {
        const sampleData = JSON.parse(sampleDataString);
        if (sampleData && Object.keys(sampleData).length > 0) {
            // 格式化为JSON字符串以便美观显示，或者可以自定义渲染逻辑
            sampleDataContentElement.textContent = JSON.stringify(sampleData, null, 2); 
        } else {
            sampleDataContentElement.textContent = '暂无数据集结构信息。';
        }
    } catch (e) {
        sampleDataContentElement.textContent = '无法解析数据集结构信息。';
        console.error('Error parsing dataset info:', e);
    }
    modal.classList.add('modal-open');
}

// 点击模态框外部关闭 (DaisyUI 默认行为，但可以加强)
const sampleModal = document.getElementById('sampleDataModal');
sampleModal.addEventListener('click', function(event) {
  if (event.target === sampleModal) {
    sampleModal.classList.remove('modal-open');
  }
});

const deleteModal = document.getElementById('deleteConfirmModal');
deleteModal.addEventListener('click', function(event) {
  if (event.target === deleteModal) {
    closeDeleteModal();
  }
});

const forceDeleteModal = document.getElementById('forceDeleteModal');
forceDeleteModal.addEventListener('click', function(event) {
  if (event.target === forceDeleteModal) {
    closeForceDeleteModal();
  }
});

// 切换数据集启用/禁用状态
function toggleDatasetActive(datasetId, isActive) {
    // 获取CSRF令牌
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    
    // 使用fetch API发送POST请求
    fetch(`/datasets/${datasetId}/toggle_active`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': csrfToken
        },
        body: JSON.stringify({ is_active: !isActive })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 显示消息
            alert(data.message);
            // 刷新页面以显示更新后的状态
            window.location.reload();
        } else {
            alert('操作失败：' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('切换数据集状态时发生错误');
    });
}

// 全局变量存储当前操作的数据集信息
let currentDatasetId = null;
let currentDatasetName = null;

// 清空当前数据集信息的辅助函数
function clearCurrentDataset() {
    currentDatasetId = null;
    currentDatasetName = null;
    console.log('Cleared current dataset variables');
}

// 删除数据集确认
function confirmDeleteDataset(button) {
    currentDatasetId = button.dataset.datasetId;
    currentDatasetName = button.dataset.datasetName;
    
    // 调试信息
    console.log('Dataset ID:', currentDatasetId);
    console.log('Dataset Name:', currentDatasetName);
    
    // 验证数据
    if (!currentDatasetId || currentDatasetId === 'undefined') {
        showErrorMessage('无法获取数据集ID，请刷新页面后重试');
        return;
    }
    
    // 设置确认消息
    document.getElementById('deleteConfirmMessage').textContent = 
        `确定要删除数据集 "${currentDatasetName}" 吗？`;
    
    // 显示删除确认模态框
    document.getElementById('deleteConfirmModal').classList.add('modal-open');
}

// 关闭删除确认模态框
function closeDeleteModal() {
    document.getElementById('deleteConfirmModal').classList.remove('modal-open');
    // 清空全局变量（用户取消操作）
    clearCurrentDataset();
}

// 执行删除
function executeDelete() {
    const datasetId = currentDatasetId; // 保存ID
    console.log('executeDelete: currentDatasetId =', currentDatasetId);
    console.log('executeDelete: datasetId =', datasetId);
    
    document.getElementById('deleteConfirmModal').classList.remove('modal-open');
    // 注意：不要在这里清空全局变量，因为可能需要强制删除
    // 只有在删除成功或用户取消时才清空
    // 执行删除
    deleteDataset(datasetId, false);
}

// 关闭强制删除模态框
function closeForceDeleteModal() {
    document.getElementById('forceDeleteModal').classList.remove('modal-open');
    // 清空全局变量（用户取消强制删除操作）
    clearCurrentDataset();
}

// 执行强制删除
function executeForceDelete() {
    const datasetId = currentDatasetId; // 保存ID
    console.log('executeForceDelete: currentDatasetId =', currentDatasetId);
    console.log('executeForceDelete: datasetId =', datasetId);
    
    document.getElementById('forceDeleteModal').classList.remove('modal-open');
    // 执行强制删除
    deleteDataset(datasetId, true);
}

// 显示强制删除确认模态框
function showForceDeleteModal(message, dependencyCount) {
    document.getElementById('forceDeleteMessage').textContent = message;
    document.getElementById('dependencyInfo').textContent = 
        `${dependencyCount} 个相关的评估数据集关联记录`;
    document.getElementById('forceDeleteModal').classList.add('modal-open');
}

// 显示成功消息的模态框
function showSuccessMessage(message) {
    // 创建临时的成功提示
    const toast = document.createElement('div');
    toast.className = 'toast toast-top toast-center';
    toast.innerHTML = `
        <div class="alert alert-success">
            <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>${message}</span>
        </div>
    `;
    document.body.appendChild(toast);
    
    // 3秒后移除提示并刷新页面
    setTimeout(() => {
        document.body.removeChild(toast);
        window.location.reload();
    }, 2000);
}

// 显示错误消息的模态框
function showErrorMessage(message) {
    const toast = document.createElement('div');
    toast.className = 'toast toast-top toast-center';
    toast.innerHTML = `
        <div class="alert alert-error">
            <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <span>${message}</span>
        </div>
    `;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        document.body.removeChild(toast);
    }, 4000);
}

// 删除数据集
function deleteDataset(datasetId, force = false) {
    // 验证数据集ID
    if (!datasetId || datasetId === 'null' || datasetId === 'undefined') {
        showErrorMessage('数据集ID无效，无法执行删除操作');
        return;
    }
    
    console.log('Deleting dataset with ID:', datasetId, 'Force:', force);
    
    const requestBody = force ? { force: true } : {};
    
    // 获取CSRF令牌
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    
    fetch(`/datasets/${datasetId}/delete`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': csrfToken
        },
        body: JSON.stringify(requestBody)
    })
    .then(response => {
        console.log('Delete response status:', response.status);
        
        // 无论状态码如何，都尝试解析JSON响应
        return response.json().then(data => ({
            status: response.status,
            ok: response.ok,
            data: data
        }));
    })
    .then(result => {
        const { status, ok, data } = result;
        console.log('Response result:', result);
        
        if (data.success) {
            // 删除成功，清空全局变量
            clearCurrentDataset();
            showSuccessMessage(data.message);
        } else if (data.has_dependencies) {
            // 有依赖关系，显示强制删除确认模态框
            // 不清空全局变量，因为用户可能选择强制删除
            showForceDeleteModal(data.message, data.dependency_count);
        } else {
            // 其他错误情况，清空全局变量
            clearCurrentDataset();
            showErrorMessage('删除失败：' + data.message);
        }
    })
    .catch(error => {
        console.error('Delete error:', error);
        // 网络错误，清空全局变量
        clearCurrentDataset();
        showErrorMessage('删除数据集时发生网络错误，请稍后重试');
    });
}

// 显示所有数据集切换
document.getElementById('showAllToggle').addEventListener('change', function() {
    // 构建新的URL
    const currentUrl = new URL(window.location.href);
    const params = new URLSearchParams(currentUrl.search);
    
    // 更新show_all参数
    if (this.checked) {
        params.set('show_all', '1');
    } else {
        params.set('show_all', '0');
    }
    
    // 保留category参数
    currentUrl.search = params.toString();
    
    // 跳转到新URL
    window.location.href = currentUrl.toString();
});
</script>
{% endblock %} 